<?php

require_once('lib/OwnedObject.php');
require_once('model/CarModel.php');

define(CAR_ELITE_NO, 	 	0);
define(CAR_ELITE_YES,		1);

define(CAR_STATUS_SALON, 	 1);
define(CAR_STATUS_ASORDER,   2);
define(CAR_STATUS_BYOWNER,   3);
define(CAR_STATUS_BYOWNER_BY,4);

define(CAR_ACTIVE_ONVIEW,   1);
define(CAR_ACTIVE_SHOW,   	2);
define(CAR_ACTIVE_ARCHIVE,  3);

$CAR_ACTIVES = array(
	CAR_ACTIVE_ONVIEW=>'На рассмотрении',
	CAR_ACTIVE_SHOW=>'Опубликовано',
	CAR_ACTIVE_ARCHIVE=>'В архиве',

);

define(CAR_STATE_EXCELLENT, 	1);
define(CAR_STATE_GOOD,   		2);
define(CAR_STATE_AFTER_REPAIR,  3);
define(CAR_STATE_CRASH, 		4);

$CAR_STATES = array(
	CAR_STATE_EXCELLENT=>'Отличное',
	CAR_STATE_GOOD=>'Хорошее',
	CAR_STATE_AFTER_REPAIR=>'После ремонта',
	CAR_STATE_CRASH=>'Аварийное'
);

class Car extends OwnedObject {
	protected $modelName = 'Car';
	protected $infoId;  // автоинкремент, номер объявления
	protected $model;     // FK -> CarModel.Id
	protected $enginev;  // объем двигателя
	protected $year;    // год выпуска
	protected $path;	// пробег
	protected $price;	// цена автомобиля
	protected $color;	// цвет текстом
	protected $state;	// состояние автомобиля (ОТЛИЧНОЕ, ХОРОШЕЕ, ПОСЛЕ РЕМОНТА, АВАРИЙНОЕ[убитая в хлам])
	protected $description; // дополнительное опциональное описание
	protected $active;	// активность позиции: (НА РАССМОТРЕНИЕ, ПОКАЗЫВАТЬ, АРХИВ)
	protected $status;	// статус автомобиля в системе (В САЛОНЕ, НА ЗАКАЗ, ЧАСТНОЕ ОБЪЯВЛЕНИЕ)
	protected $elite;	// является ли объявление элитным(ротация в верхних баннерах)

	public static function Install() {
            ModelObject::Install();
            CarModel::Install();

			$query = sprintf("CREATE TABLE `Car` (
									`Id` INT( 32 ) unsigned NOT NULL,
									`infoId` INT( 32 ) unsigned NOT NULL auto_increment,
									`Model` INT( 32 ) unsigned NOT NULL,
									`enginev` INT( 16 ),
									`year` INT( 16 ),
									`path` INT( 32 ),
									`price` INT( 32 ),
									`color` VARCHAR(50),
									`state` INT( 4 ),
									`description` TEXT,
									`active` INT( 4 ) NOT NULL ,
									`status` INT( 4 ) NOT NULL ,
									`elite` INT( 4 ) NOT NULL ,
									UNIQUE KEY  ( `Id` ),
									PRIMARY KEY ( `infoId` ),
									FOREIGN KEY ( `Id` ) REFERENCES `Object`(`Id`) ON DELETE CASCADE,
									FOREIGN KEY ( `Model` ) REFERENCES `CarModel`(`Id`)
									) ENGINE=INNODB DEFAULT CHARSET=utf8;
								");
			//file_put_contents('dump.sql', $query);
			mysql_query($query);

			$query = sprintf("INSERT INTO `ObjectType` SET `name` = '%s'", strval(__CLASS__));
			mysql_query($query);

			echo "Car object installed\n";
	}

	public function Load() {


                if(!isset($this->infoId)){
                	$query = sprintf("SELECT
										`Id`,`infoId`, `Model`, `enginev` , `year` , `path` , `price`,
										`color` , `state` , `description` , `active` , `status`, `elite`
								FROM
									`Car`
								WHERE
									`Id` =%d", $this->id);
                }
                else{
                	$query = sprintf("SELECT
										`Id`,`infoId`, `Model`, `enginev` , `year` , `path` , `price`,
										`color` , `state` , `description` , `active` , `status`, `elite`
								FROM
									`Car`
								WHERE
									`infoId` =%d", $this->infoId);
                }

                $res = mysql_query($query);
                $row = mysql_fetch_array($res);

                $this->id = $row[0];

                parent::Load();

                $this->infoId = $row[1];
                $this->model = $row[2];
                $this->enginev = $row[3];
                $this->year = $row[4];
                $this->path = $row[5];
                $this->price = $row[6];
                $this->color = $row[7];
                $this->state = $row[8];
                $this->description = $row[9];
                $this->active = $row[10];
                $this->status = $row[11];
                $this->elite = $row[12];
	}

	public function RegisterObject(){
				$obj_id= parent::RegisterObject();

				$parse = mysql_query('select MAX(`infoId`) from `Car`');
				$res = mysql_fetch_array($parse);
				$this->infoId = (int)$res[0] + 1;

							
				$query=sprintf("INSERT INTO
										`Car` ( `Id`, `infoId`, `Model` , `enginev` , `year` , `path` , `price` ,
										`color` , `state` , `description` , `active` , `status`, `elite` )
									VALUES (%d, %d, %d, %d, %d, %d, %d, '%s', %d, '%s', %d, %d, %d)
					", $obj_id, $this->infoId, $this->model, $this->enginev, $this->year, $this->path,
					 $this->price, mes($this->color), $this->state, mes($this->description),
					 $this->active, $this->status, $this->elite);
				mysql_query($query);
	}

    public function Model($newModel=false) {
            if($newModel){
            	if($newModel instanceof CarModel)
                    $this->model = $newModel->Id();
                else throw new Exception("Invalid argument CarModel instance required");
            }

            $Model = new CarModel($this->model);
            if(!$newModel) $Model->Load();
            return $Model;
    }

    public function Enginev($newEnginev=false) {
            if($newEnginev)
                    $this->enginev = $newEnginev;
            return $this->enginev;
    }

    public function Year($newYear=false) {
            if($newYear)
                    $this->year = $newYear;
            return $this->year;
    }

    public function InfoId($newInfoId=false) {
            if($newInfoId)
                    $this->infoId = $newInfoId;
            return $this->infoId;
    }

    public function Path($newPath=false) {
            if($newPath)
                    $this->path = $newPath;
            return $this->path;
    }

    public function Price($newPrice=false) {
            if($newPrice)
                    $this->price = $newPrice;
            return $this->price;
    }

    public function Color($newColor=false) {
            if($newColor)
                    $this->color = $newColor;
            return $this->color;
    }

    public function State($newState=false) {
            if($newState)
                    $this->state = $newState;
            return $this->state;
    }

    public function Description($newDescription=false) {
            if($newDescription)
                    $this->description = $newDescription;
            return $this->description;
    }

    public function Active($newActive=false) {
            if($newActive)
                    $this->active = $newActive;
            return $this->active;
    }

    public function Status($newStatus=false) {
            if($newStatus)
                    $this->status = $newStatus;
            return $this->status;
    }
    
    public function Elite($newElite='none') {
            if($newElite!='none')
                    $this->elite = $newElite;
        
            return $this->elite;
    }

	public function AsSource($otherName = 'Car'){

				global $CAR_STATES,$CAR_ACTIVES;

				$result = parent::AsSource($otherName);

				$Model = new CarModel($this->model);
				$Model->Load();
				$result -> MountSource($Model->AsSource(),'Model');

				$result -> Attribute('infoid',$this->infoId);
				$result -> Attribute('enginev',$this->enginev);
				$result -> Attribute('year',$this->year);
				$result -> Attribute('path',$this->path);
				$result -> Attribute('price',$this->price);
				$result -> Attribute('color',$this->color);
				$result -> Attribute('description',$this->description);
				$result -> Attribute('status',$this->status);
				$result -> Attribute('color',$this->color);
				$result -> Attribute('elite',$this->elite);

				$state = new XmlSource('state');
				$state->Attribute('id', $this->state);
				$state->Attribute('description', $CAR_STATES[$this->state]);

				$active = new XmlSource('active');
				$active->Attribute('id', $this->active);
				$active->Attribute('description', $CAR_ACTIVES[$this->active]);

				$result->MountSource($state);
				$result->MountSource($active);
				
				$author = new User($this->Owner());
				$author->Load();

				$result->MountSource($author->AsSource('Author'));

				return $result;
	}

	public function Remove(){
		$query=sprintf("delete from `Car` where `Id`=%d",$this->id);
		mysql_query($query);
		parent::Remove();
	}

    public function Save() {
            parent::Save();
            $query = sprintf("
                            UPDATE `Car`
                            SET
                                    `infoId`=%d,
                                    `Model`=%d,
                                    `enginev`=%d,
                                    `year`=%d,
                                    `path`=%d,
                                    `price`=%d,
                                    `color`='%s',
                                    `state`=%d,
                                    `description`='%s',
                                    `active`=%d,
                                    `status`=%d,
                                    `elite`=%d

                            WHERE
                                    `Id`=%d",
                           $this->infoId, $this->model, $this->enginev, $this->year, $this->path, $this->price, mes($this->color), $this->state, mes($this->description), $this->active, $this->status, $this->elite, $this->id
                    );
                    
          	mysql_query($query);
    }
    
    

	public static function CarsByDeveloper($developerAlias='', $status=CAR_STATUS_SALON, $active=CAR_ACTIVE_ONVIEW, $num=20){

		$query = sprintf("SELECT `Id` FROM `Car` WHERE `status`=%d and `active`=%d LIMIT %d", $status, $active, $num);

		if($developerAlias!=''){
			$query = sprintf("SELECT c.`Id`
						FROM `Car` c, `CarModel` cm, `CarDeveloper` cd
						WHERE c.`Model` = cm.`Id` and cm.`Developer` = cd.`Id` and
						c.`status`=%d and c.`active`=%d and cd.`alias`='%s' LIMIT %d", $status, $active, $developerAlias, $num);
		}
		$parse = mysql_query($query);

		$cars = new XmlSource('Cars');
		while($result = mysql_fetch_assoc($parse)){
			$car_id = $result['Id'];
			$car = new Car($car_id);
			$car->Load();
			$cars->MountSource($car->AsSource());
		}

		return $cars;
	}
	
	//частные объявления
	public static function Declarations($num=3){
		$query = sprintf("SELECT `Id` FROM `Car` WHERE `status`=%d and `active`=%d ORDER BY rand() LIMIT %d",
		CAR_STATUS_BYOWNER, CAR_ACTIVE_SHOW, $num);		
		
		$parse = mysql_query($query);
		
		$cars = new XmlSource('Cars-declarations');
		while($result = mysql_fetch_assoc($parse)){
			$car_id = $result['Id'];
			$car = new Car($car_id);
			$car->Load();
			$cars->MountSource($car->AsSource());
		}

		return $cars;		
	}
	
	public static function OwnCars($num=10){

		$query = sprintf("SELECT c.`Id` FROM `Car` c, `Object` o WHERE c.`Id`=o.`id` AND o.`owner` = %d LIMIT %d", $_SESSION['userid'], $num);
		$parse = mysql_query($query);

		$cars = new XmlSource('Cars');
		while($result = mysql_fetch_assoc($parse)){
			$car_id = $result['Id'];
			$car = new Car($car_id);
			$car->Load();
			$cars->MountSource($car->AsSource());
		}

		return $cars;
	}
	

	public static function CreateCarFish($num){
		$cmodel=3;

		$developer=array("Mazda", "VAZ", "Audi", "KaMAZ", "Opel", "Renault", "BMW", "Chrailser");
		$model=array("6", "2111", "21106", "TT", "720i", "300C", "Astra", "Megane", "Kalina", "A6", "A8", "535i");
		$enginev=array("800", "1200", "1000", "1600", "2000", "1800", "2300", "2600", "2400", "3000");
		$year=array("1900", "1978", "2004", "2005", "2006", "2007", "1543", "1278");
		$path=array("350234", "3424", "1235", "43543", "92635", "433930", "437634", "2783", "383", "328723", "324748", "2338378");
		$price=array("10000", "20000", "35000", "89203", "34040", "102000", "3039", "18000");
		$color=array("red", "green", "blue", "yellow", "magneta", "white", "black");
		$description=array("Просто бульдозер", "Бронетранспортер", "Настоящая ласточка", "Крутая тачушка", "Не машина, а самолет");
		$state=array('1','2','3','4');
		$active=array('1','2','3');  //== status

		$cd=count($developer)-1;
		$cm=count($model)-1;
		$ce=count($enginev)-1;
		$cy=count($year)-1;
		$cp=count($path)-1;
		$cpr=count($price)-1;
		$cc=count($color)-1;
		$cs=count($state)-1;
		$cdes=count($description)-1;
		$ca=count($active)-1;

		for($i=0;$i<$cd;$i++){
			$obj = new CarDeveloper();
			$obj->Alias($developer[$i]);
			$obj->Name($developer[$i]);
			$obj->Save();
			$developer[$i]=$obj;

			$arr=array();

			for($j=0;$j<$cmodel;$j++){
				$k=rand(0,$cm);
				while(in_array($k,$arr)){
					$k=rand(0,$cm);
				}
				$arr[]=$k;
				$m = new CarModel();
				$m->Developer($obj);
				$m->Name($model[$k]);
				$m->Save();
				$newmodel[]=$m;
			}
		}
		$cm=count($newmodel)-1;

		for($i=0;$i<$num;$i++){
			$car = new Car();
			$model=$newmodel[rand(0,$cm)];
			$car->Model($model);
			$car->Enginev($enginev[rand(0,$ce)]);
			$car->Year($year[rand(0,$cy)]);
			$car->Path($path[rand(0,$cp)]);
			$car->Price($price[rand(0,$cpr)]);
			$car->Color($color[rand(0,$cc)]);
			$car->State($state[rand(0,$cs)]);
			$car->Description($description[rand(0,$cdes)]);
			$car->Active($active[rand(0,$ca)]);
			$car->Status($active[rand(0,$ca)]);
			$car->Save();
			
			$new_dir = $_SERVER['DOCUMENT_ROOT'].'/media/cars/'.$car->Id();
			mkdir($new_dir);
			$new_path = $new_dir.'/small.jpg';
			copy($_SERVER['DOCUMENT_ROOT'].'/images/car4.jpg', $new_path);
			$im = imagecreatefromjpeg($new_path);
			imagestring($im,10,3,3,$model->Name(),10);
			imagejpeg($im,$new_path);
			if($car->Status() == CAR_STATUS_SALON && rand(0,10)<5){
				$new_path = $new_dir.'/big.jpg';
				copy($_SERVER['DOCUMENT_ROOT'].'/images/top-bann2.jpg', $new_path);
				$im = imagecreatefromjpeg($new_path);
				imagestring($im,10,3,3,$model->Name(),imagecolorallocate($im, 255, 0, 0));
				imagejpeg($im,$new_path);				
				$car->Elite(CAR_ELITE_YES);
				$car->Save();
			}
		}

	}
	

	public static function States(){
		
		global $CAR_STATES;
	
		$states = new XmlSource('all-states');
		for($i=1; $i<=count($CAR_STATES);$i++){
			$item = new XmlSource('state');
			$item->Attribute('id',$i);
			$item->Attribute('name', $CAR_STATES[$i]);
			$states->MountSource($item);
		}
		
		return $states;
	
	}			
	
	
	public static function SalonDevelopers(){
	
		$query = sprintf("
SELECT
distinct(cd.`Id`)
FROM
`Car` c
JOIN `CarModel` cm ON cm.`Id`= c.Model
JOIN `CarDeveloper` cd ON cd.`Id`= cm.Developer
WHERE
c.`status` = %d	and c.`active`=%d
		",CAR_STATUS_SALON, CAR_ACTIVE_SHOW);
		
		$parse = mysql_query($query);
	
		$cars = new XmlSource('salon-developers');
		while($result = mysql_fetch_assoc($parse)){
			$item = new CarDeveloper($result['Id']);
			$item->Load();
			$itemAsSource = $item->AsSource();
			if(replace_link($_SERVER['REQUEST_URI']) == $item->Alias())
				$itemAsSource ->Attribute('selected','selected');
			$cars->MountSource($itemAsSource);
		}
		
		return $cars;
	
	}

	public static function GetElitCar(){
		$query = sprintf("SELECT `Id` FROM `CAR` WHERE `elite`=%d ORDER BY rand() LIMIT 3", CAR_ELITE_YES);
		$parse = mysql_query($query);
		
		$elitcar = new XmlSource('elit-cars');
		
		while ($rezult = mysql_fetch_assoc($parse)) {
			$car = new Car($rezult['Id']);
			$car->Load();
			$elitcar->MountSource($car->AsSource());
		}
		
		return $elitcar;
		
	}


}
?>